#!/bin/bash

read -p "请输入发布的环境🚀:" env
read -p "请输入发布的分支/Tag🔖:" tag
#配置参数
#接口
api_url="http://drone.dev.iybot.com" 
#用于发布的uri
deploy_uri="${api_url}/api/repos/cicd/system-admin/builds?branch=${env}&tag=${tag}"   
#用于获取发布结果的uri         
build_nuber=0     
deploy_res_uri="${api_url}/api/repos/cicd/system-admin/builds/" 
#最大重试次数
max_retry=60 
#重试间隔
retry_interval=10 
#接口请求超时时间
timeout=10 
continue_loop=true

#发布
response=$(curl -s -m $timeout -X POST "${deploy_uri}" -H "Authorization: Bearer cTWQvmNFpNWGoQKplUQpAzCBE0g7p7tR")
if [ $? -ne 0 ]; then
    echo -e "\033[31m📦  Create build failed \x1b[0m"
    exit 0 # 结束脚本
fi
status=$(echo "$response" | jq -r '.status')
build_nuber=$(echo "$response" | jq -r '.number')
if [ "$status" != 'pending' ];then
    echo -e "\033[31m Create build failed \x1b[0m, status: ${status}"
    exit 0 # 结束脚本
fi
time=$(date +"%Y-%m-%d %H:%M:%S")
echo -e "\033[32m📦 Create build successfully,${time} \x1b[0m"

#查看发布结果
for ((i=1; i<=max_retry; i++)); do
    response=$(curl -s -m $timeout "${deploy_res_uri}${build_nuber}" -H "Authorization: Bearer cTWQvmNFpNWGoQKplUQpAzCBE0g7p7tR")
    # 使用jq解析JSON响应
    # 假设我们检查返回JSON中的"status"字段是否为"completed"
    status=$(echo "$response" | jq -r '.status')
    if [ "$status" == "success" ]; then
        time=$(date +"%Y-%m-%d %H:%M:%S")
        echo -e "\033[32m🚀 Deploy successfully,${time} \x1b[0m"
        continue_loop=false
        break
    fi

    if [[ "$status" != "success" && "$status" != "running" ]]; then
         echo -e "\033[31m🥅  Deploy failed,${time} \x1b[0m"
         break
    fi

    sleep $retry_interval
    time=$(date +"%Y-%m-%d %H:%M:%S")
    echo -e "\033[32m🚧 wait deploy result,${time}\x1b[0m"
done

# 检查是否因为达到最大重试次数而退出
if [ "$continue_loop" == true ]; then
    time=$(date +"%Y-%m-%d %H:%M:%S")
    echo -e "\033[31m🥅 已达到最大重试次数${max_retry},终止查询,${time}\x1b[0m"
fi